package com.gogowan.agroenterprise.storage;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.StoreListResult;
import com.gogowan.agroenterprise.model.StoreModel;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 货位添加
 * 
 * @author tjh 2017-01-06
 *
 */
public class GoodsAllocationAddActivity extends Activity implements
		View.OnClickListener {
	private LinearLayout rootLinear;
	private int addViewID = 0;
	private List<Integer> addViewIDList = new ArrayList<Integer>();
	private TextView ckmcEdit, ckbmEdit;
	private ProgressDialog progressDialog;
	
	private long pstoreID;
	// 界面入口：add;info
	private String jmrkStr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_goods_allocation_add);

		initView();
		initValue();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		rootLinear = (LinearLayout) findViewById(R.id.goods_allocation_add_linear);
		ckmcEdit = (TextView) findViewById(R.id.goods_allocation_add_ckmc_text);
		ckbmEdit = (TextView) findViewById(R.id.goods_allocation_add_ckbm_text);

		TextView wc = (TextView) findViewById(R.id.goods_allocation_add_wc_btn);
		wc.setOnClickListener(this);

		Button tjBtn = (Button) findViewById(R.id.goods_allocation_add_zjhw_btn);
		tjBtn.setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {
		pstoreID = this.getIntent().getLongExtra("pstoreID", 0);
		jmrkStr = this.getIntent().getStringExtra("jmrkStr");

		ckmcEdit.setText(this.getIntent().getStringExtra("storenaem"));
		ckbmEdit.setText(this.getIntent().getStringExtra("storecode"));
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.goods_allocation_add_zjhw_btn:
			// 增加货位
			final View view = LayoutInflater.from(
					GoodsAllocationAddActivity.this).inflate(
					R.layout.activity_add_location_info, null);
			final int position = addViewID;
			view.setId(addViewID);
			rootLinear.addView(view);

			TextView scBtn = (TextView) view
					.findViewById(R.id.add_location_info_sc_text);
			scBtn.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					rootLinear.removeView(view);
					addViewIDList.remove((Integer) position);
				}
			});

			addViewIDList.add(addViewID);
			addViewID++;
			break;
		case R.id.goods_allocation_add_wc_btn:
			// 添加完成
			if (addViewIDList.size() == 0) {
				Toast.makeText(this, "请添加货位信息", Toast.LENGTH_LONG).show();
			} else {
				View view1;
				boolean isEmpty = false;
				List<String> mcList = new ArrayList<String>();
				for (int i = 0; i < addViewIDList.size(); i++) {
					view1 = rootLinear.findViewById(addViewIDList.get(i));
					EditText mc = (EditText) view1
							.findViewById(R.id.add_location_info_mc_edit);
					mcList.add(mc.getText() + "");
					if (TextUtils.isEmpty(mc.getText())) {
						isEmpty = true;
						break;
					}

				}

				if (isEmpty) {
					Toast.makeText(this, "请输入货位名称", Toast.LENGTH_LONG).show();
				} else {
					if (mcList.size() == 1) {
						if (mcList.get(0).equalsIgnoreCase(
								ckmcEdit.getText() + "")) {
							Toast.makeText(this, "货位名称、仓库名称不可重复", Toast.LENGTH_LONG).show();
						} else {
							addStory();
						}
					} else {
						boolean isCom = false;
						for (int i = 0; i < mcList.size() - 1; i++) {
							for (int x = i + 1; x < mcList.size(); x++) {
								if (mcList.get(i).equals(mcList.get(x))) {
									isCom = true;
									break;
								}
							}

							if (mcList.get(i).equalsIgnoreCase(
									ckmcEdit.getText() + "")) {
								isCom = true;
								break;
							}
						}

						if (mcList.get(mcList.size() - 1).equalsIgnoreCase(
								ckmcEdit.getText() + "")) {
							isCom = true;
						}
						if (isCom) {
							Toast.makeText(this, "货位名称、仓库名称不可重复", Toast.LENGTH_LONG).show();
						} else {
							addStory();
						}
					}
				}
				mcList.clear();
				mcList = null;
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 添加仓库
	 */
	private void addStory() {
		progressDialog = ProgressDialog.show(this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);

		StoreModel storeModel = new StoreModel();
//		storeModel.setEnterprise_Info_ID(loginResultInfo.getEnterpriseinfo()
//				.getEnterpriseid());
//		storeModel.setDealerID(loginResultInfo.getEnterpriseinfo()
//				.getDealerId());
		storeModel.setStoreName(ckmcEdit.getText() + "");
		storeModel.setType(2);
		storeModel.setAddUser(MyApplication.mSettings.getLong("personid",0));
		storeModel.setStoreCode(ckbmEdit.getText() + "");
//		storeModel.setUserType(loginResultInfo.getEnterpriseinfo()
//				.getUserType());

		StoreListResult storeListResult = new StoreListResult();
		List<StoreModel> storeList = new ArrayList<StoreModel>();
		StoreModel storeModel2;
		View view1;
		for (int i = 0; i < addViewIDList.size(); i++) {
			view1 = rootLinear.findViewById(addViewIDList.get(i));
			EditText mc = (EditText) view1
					.findViewById(R.id.add_location_info_mc_edit);

			storeModel2 = new StoreModel();
//			storeModel2.setEnterprise_Info_ID(loginResultInfo
//					.getEnterpriseinfo().getEnterpriseid());
//			storeModel2.setDealerID(loginResultInfo.getEnterpriseinfo()
//					.getDealerId());
			storeModel2.setStoreName(mc.getText() + "");
			storeModel2.setParentCode(pstoreID);
			storeModel2.setType(2);
			storeModel2.setAddUser(MyApplication.mSettings.getLong("personid",0));
//			storeModel2.setUserType(loginResultInfo.getEnterpriseinfo()
//					.getUserType());
			storeList.add(storeModel2);
		}
		storeListResult.setStoreList(storeList);
		storeModel.setGoods(storeListResult);

		SaveWarehouseAsyn saveWarehouseAsyn = new SaveWarehouseAsyn();
		saveWarehouseAsyn.execute(storeModel);
	}

	/**
	 * 添加仓库
	 * 
	 * @author tjh
	 *
	 */
	private class SaveWarehouseAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(GoodsAllocationAddActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(GoodsAllocationAddActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					StoreModel storeModel = (StoreModel) Utils.fromJSON(string,
							StoreModel.class);
					if (storeModel.getResult() == 21400) {
						Intent intent = new Intent(
								GoodsAllocationAddActivity.this,
								GoodsAllocationAddFinishActivity.class);
						intent.putExtra("storeModelString", string);
						GoodsAllocationAddActivity.this.startActivityForResult(
								intent, 320);
					}
					Toast.makeText(GoodsAllocationAddActivity.this,
							storeModel.getResultinfo(), Toast.LENGTH_LONG)
							.show();
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreModel storeModel = (StoreModel) params[0];
			String json = Utils.toJSON(storeModel);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					21400, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 320:
				Intent intent;
				if (jmrkStr.equals("add")) {
					// 继续添加入口
					intent = new Intent(this, WarehouseInfoActivity.class);
					intent.putExtra("storeid", pstoreID);
					intent.putExtra("storenaem", ckmcEdit.getText() + "");
					this.startActivity(intent);
				} else if (jmrkStr.equals("info")) {
					// 详情入口
					intent = new Intent(this, WarehouseInfoActivity.class);
					setResult(RESULT_OK, intent);
				}
				this.finish();
				break;
			default:
				break;
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 返回键
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
